<template>
<div class="container">
    <div class="row">
       <p class="form-inline">
          <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" v-on:click="AddGroupItem()">新增</button>&nbsp;&nbsp;     
             <select id="group_res_type_id" class="form-control custom-select" v-model="res_type_id" @change="goPage">
                    <option value='0' selected>请选择...</option>
                    <option v-for="resType in resTypes" :value="resType.id">{{ resType.name }}</option>
            </select>
       </p> 
    </div>
    <div class="row">
<table class="table">
  <thead class="thead-light">
    <tr>     
      <th scope="col">资源</th>
      <th scope="col">字符串</th>
      <th scope="col">资源类型</th>
      <th scope="col">描述</th>
      <th scope="col">创建</th>      
      <th scope="col">编辑</th>
      <th scope="col">删除</th>
    </tr>
  </thead>
  <tbody>

      <template v-if="paginator.total > 0" v-for="(item, index) in items">
        <tr>
          <td><i class="fa fa-folder-open-o" aria-hidden="true"></i> {{ item.name }}</td>
          <td>{{ item.res_string }}</td>
          <template v-for="resType in resTypes">
          	<td v-if="resType.id===item.res_type_id" v-text="resType.name"></td>
          </template>
          <td>{{ item.description }}</td>
          <td>{{ item.created_at }}</td>
          <td><button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#exampleModal" v-on:click="editGroupItem(index,null)">编辑</button></td>
          <td><button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#exampleModalCenter" v-on:click="removeGroupItem(index,null)">删除</button></td>
        </tr>
 
        <tr v-if="item.childrens" v-for="(citem,cindex) in item.childrens" class="child-item">
            <td class="child-title"><i class="fa fa-folder-o" aria-hidden="true"></i> {{ citem.name }}</td>
          <td>{{ citem.res_string }}</td>
          <template v-for="resType in resTypes">
            <td v-if="resType.id===citem.res_type_id" v-text="resType.name"></td>
          </template>
          <td>{{ citem.description }}</td>
          <td>{{ citem.created_at }}</td>
          <td><button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#exampleModal" v-on:click="editGroupItem(index,cindex)">编辑</button></td>
          <td><button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#exampleModalCenter" v-on:click="removeGroupItem(index,cindex)">删除</button></td>
        </tr>

      </template>
  
</tbody>
</table>


    <ul v-if="paginator.total > 0" class="pagination">
            <li v-if="paginator.prev_page_url" class="page-item"><a class="page-link" v-on:click="goToPage(paginator.prev_page_url)" rel="prev">&lsaquo;</a></li>   
            <li v-else class="page-item disabled"><span class="page-link">&lsaquo;</span></li>
            <select class="form-control custom-select" v-model="paginator.current_page" @change="goPage">
                    <option v-for="index in paginator.last_page" v-bind:value="index">{{ index }}</option>
            </select>
            <li  v-if="paginator.next_page_url" class="page-item"><a class="page-link" v-on:click="goToPage(paginator.next_page_url)"  rel="next">&rsaquo;</a></li>
            <li  v-else class="page-item disabled"><span class="page-link">&rsaquo;</span></li>
    </ul>


<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">提示</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        确定要删除资源<code>{{ selectItem.name }}</code>?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" v-on:click="ConfirmRemoveGroupItem()">确定</button>
      </div>
    </div>
  </div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{ actionName }}</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close" v-on:click="cancelEditItem()">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
         <b-form @submit="updateGroupItem" @reset="onReset" v-if="show">
          <div class="form-group">
            <label for="group-name" class="col-form-label">名称:</label>
            <input type="hidden" class="form-control" id="group-id" v-model="selectItem.id">
            <input type="text" class="form-control" required id="group-name" v-model="selectItem.name">
          </div>


          <div class="form-group" v-if="api_type!=null && selectItem.res_type_id!=api_type.id">
            <label for="group-description" class="col-form-label">依赖接口:</label>

             <b-form-checkbox-group id="checkboxes1" name="group-resources" value-field="id" text-field="name" v-model="multipleSelect" :options="childrens">
             </b-form-checkbox-group>

          </div>
          <div class="form-group">
            <label for="group-description" class="col-form-label">资源类型:</label>
            <select class="form-control" required id="group-description" v-model="selectItem.res_type_id">              
            	<option v-for="resType in resTypes" v-bind:value="resType.id">{{ resType.name }}</option>
            </select>
          </div>
          <div class="form-group">
            <label for="group-res_string" class="col-form-label">资源字符串:</label>
            <select class="form-control" id="group-res_string" v-model="routeSelectIndex">
            	<option v-for="(route,index) in routes" v-bind:value="index">{{ route.uri }}</option>
            </select>
          </div>
          <div class="form-group">
            <label for="group-description" class="col-form-label">描述:</label>
            <b-form-input class="form-control" required id="group-description" v-model="selectItem.description"></b-form-input>
          </div>
          <b-button type="submit" variant="primary">提交</b-button> <b-button type="reset" v-if="!isEdit" variant="danger">重置</b-button> 
        </b-form>
      </div>
      <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>   
      </div>
    </div>
  </div>
</div>


    </div>
</div>
</template>

<style type="text/css">
.child-title{
  position:relative;
  margin-left:20px;
  text-indent:8px;
}
.child-title::before {
    content: ""; position: absolute; width: 1px; height: 100%; background-color: silver; border: none; left: 15px; top: -25px; z-index: 1;
 }
.child-title::after {
    content: ""; left: 15px; position: absolute; right: auto; background-color: silver; height: 1px; top: 27px; width: 12px; z-index: 1; 
 }
.child-item td{border-top:0px;} 
</style>

<script>
    export default {
    	data(){
    		return {
                actionName:'编辑_资源',
                selectItem:{},
                isEdit:false,
                resTypes:[],
                api_type:null,
                res_type_id:0,
                show:true,
                routes:[],
                childrens:[],
                multipleSelect:[],
                oldmultipleSelect:[],
                routeSelectIndex:-1,
                selectIndex:-1,
                selectCIndex:-1,
                paginator:{},
    			      items:[]
    		}
    	},
        mounted() {
            this.goToPage('/rbac/resource/apiIndex');
            console.log('Component mounted.')
        },
        methods: {  
            AddGroupItem : function(){
                this.actionName='新增_资源';
                this.selectItem={};
                this.isEdit=false;
            },onReset (evt) {
              evt.preventDefault();
              /* Reset our form values */
              this.selectItem = {};
              /* Trick to reset/clear native browser form validation state */
              this.show = false;
              this.$nextTick(() => { this.show = true });
            },
            editGroupItem : function(index,cindex){
                const items=this.items;
                var selectItem = null;
                if(cindex!=null){
                  selectItem=Object.assign({},items[index].childrens[cindex]);
                }else{
                  selectItem = Object.assign({},items[index]);
                }
                var multipleSelect=[];
                _.forEach(selectItem.childrens,function(value){
                    multipleSelect.push(value.id);
                });  
                this.multipleSelect=multipleSelect;  
                this.oldmultipleSelect=multipleSelect;                            
                this.selectItem=selectItem;
                this.selectIndex=index;
                this.selectCIndex=cindex;
                this.actionName='编辑_资源';
                this.routes.unshift({uri:selectItem.res_string});
                this.routeSelectIndex=0;
                this.isEdit=true;
            }, 
            cancelEditItem : function(){
                if(this.routeSelectIndex>-1&&this.isEdit){
                  this.routes.splice(this.routeSelectIndex,1);
                }
            },
            ConfirmRemoveGroupItem : function (){
                console.log(this.selectIndex);
                var selectItem=this.items[this.selectIndex];
                var cindex=this.selectCIndex;
                if(cindex!=null&&cindex!=-1){
                  selectItem=selectItem.childrens[cindex];
                }
                var that=this;
                axios.post('/rbac/resource/apiDelete/'+selectItem.id)
                  .then(function (response) {  
                    var res_string='';
                    if(that.selectCIndex!=null&&that.selectCIndex!=-1){
                      res_string=that.items[that.selectIndex].childrens[that.selectCIndex].res_string;
                      that.items[that.selectIndex].childrens.splice(that.selectCIndex,1);
                    }else{
                      res_string=that.items[that.selectIndex].res_string;
                      that.items.splice(that.selectIndex,1);
                    }    
                    that.routes.push({name:res_string,uri:res_string});                       
                    $('#exampleModalCenter').modal('hide');
                  })
                  .catch(function (error) {
                    console.log(error);
                  });
            },
            updateGroupItem : function (evt){
                evt.preventDefault();
                var that=this;
                var res_string='javascript:;'
                if(that.routeSelectIndex>-1){
                  res_string=that.routes[that.routeSelectIndex].uri;
                }

                var pids=_.difference(that.multipleSelect,that.oldmultipleSelect);
                var oldpids=_.difference(that.oldmultipleSelect,that.multipleSelect);

                axios.post('/rbac/resource/apiStore', {
                    id:that.selectItem.id,
                    name:that.selectItem.name,
                    res_type_id:that.selectItem.res_type_id,
                    res_string:res_string,
                    pids:pids,
                    oldpids:oldpids,
                    description:that.selectItem.description
                  })
                  .then(function (response) { 
                    if(that.routeSelectIndex>-1){
                      that.routes.splice(that.routeSelectIndex,1); 
                    }     

                    var childrens=that.childrens;


                    _.forEach(oldpids,function(value){
                      _.forEach(childrens,function(o){
                        if(o.id===value){
                          o.pid=0;
                          console.log(o.name+'-diff-'+o.res_string);
                          that.items.push(o);
                          return;
                        }
                      });
                    });

           
                    _.forEach(pids,function(value){
                      //
                      _.remove(that.items, function(item) {
                        return item.id == value;
                      });

                      _.forEach(childrens,function(o){
                        if(o.id===value){
                          o.pid=that.selectItem.id;
                          console.log(o.name+'-add-'+o.res_string);
                          return;
                        }
                      });
                    });
                    var items=that.items;

                    if(that.selectCIndex!=null&&that.selectCIndex!=-1){                      
                      console.log('edit child...');
                      //如果更新的是api  children里更新返回结果
                        if(response.data.res_type_id==that.api_type.id){
                          console.log('更新的是api  childrens里更新返回结果1');

                          for (var i = 0; i < childrens.length; i++) {
                            if(childrens[i].id==response.data.id){
                              childrens[i]=response.data;
                              i=childrens.length;
                            }
                          }

                        } 
                    }else{
                      //获取当前编辑item的childrens
                       _.forEach(items, function(value) {
                          _.forEach(pids,function(o){
                            _.remove(value.childrens, function(e) { return e.id==o; });
                          });      
                      });

                      var tmp=_.filter(childrens, function(o) { return o.pid===response.data.id; });
                      response.data.childrens=tmp;    

                      if(that.selectItem.id){
                        that.selectItem=response.data;              
                        items[that.selectIndex]=that.selectItem;   
                        //如果更新的是api  children里更新返回结果
                        if(response.data.res_type_id==that.api_type.id){
                          console.log('更新的是api  childrens里更新返回结果2');
                          for (var i = 0; i < childrens.length; i++) {
                            if(childrens[i].id==response.data.id){
                              childrens[i]=response.data;
                              i=childrens.length;
                            }
                          }
                        }        
                      }else{
                        items.push(response.data);
                        //如果添加的是api  children里增加返回结果
                        if(response.data.res_type_id==that.api_type.id){
                          that.childrens.push(response.data);
                        }
                      }
                    }
                    

                    

                    if(that.selectCIndex!=null&&that.selectCIndex!=-1){
                      console.log('edit ... child...');
                      that.selectItem=response.data;
                      console.log(that.selectIndex+' '+that.selectCIndex);
                      items[that.selectIndex].childrens[that.selectCIndex]=response.data; 
                    }

                    that.items=items;
                    that.childrens=childrens;
                    that.selectIndex=-1;
                    that.selectCIndex=-1;
                    that.multipleSelect=[];                    
                    that.oldmultipleSelect=[];      
                    $('#exampleModal').modal('hide');
                  })
                  .catch(function (error) {
                    console.log(error);
                  });
            }, 
            removeGroupItem : function (index,cindex) {
                this.selectIndex=index;
                this.selectCIndex=cindex;
            },
            goPage : function (event){
                var url=this.paginator.path+'?page='+this.paginator.current_page;
                this.goToPage(url);
            },
            goToPage : function (url){
                console.log(url);
                var that=this;
                axios.get(url,{params : { res_type_id:that.res_type_id }})
                 .then(function (response) {
                 	var res=response.data;
                    var items=res.data.data;
                    that.resTypes=res.ResTypes;
                    that.routes=res.routes;
                    that.childrens=res.childrens;
                    that.api_type=res.api_type;

                    _.forEach(items, function(value) {
                        var tmp=_.filter(that.childrens, function(o) { return o.pid===value.id; });
                        value.childrens=tmp;       
                    });
                    that.items=items;

                    that.paginator={
                        current_page:res.data.current_page,
                        first_page_url:res.data.first_page_url,
                        from:res.data.from,
                        to:res.data.to,
                        last_page:res.data.last_page,
                        last_page_url:res.data.last_page_url,
                        next_page_url:res.data.next_page_url,
                        path:res.data.path,
                        per_page:res.data.per_page,
                        prev_page_url:res.data.prev_page_url,
                        total:res.data.total,
                    };


                 })
                 .catch(function (error) {
                    console.log(error);
                 });
            }
        }
    }
</script>